package com.loongxun.playwithyou.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.util.ReflectionUtils;
import com.loongxun.playwithyou.util.ToastView;
import com.tencent.mm.opensdk.diffdev.DiffDevOAuthFactory;
import com.tencent.mm.opensdk.diffdev.IDiffDevOAuth;
import com.tencent.mm.opensdk.diffdev.OAuthErrCode;
import com.tencent.mm.opensdk.diffdev.OAuthListener;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import cz.msebera.android.httpclient.util.TextUtils;

/**
 * 登录
 * Created by Administrator on 2017/7/17.
 */
public class LoginActivity extends Activity implements View.OnClickListener{

    private Context context;
    private SharedPreferences shared;
    private SharedPreferences.Editor editor;
    private SendRequest send;

    //账号，密码
    private EditText et_login_phone,et_login_pass;
    private String phone,pass;

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private IDiffDevOAuth oauth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        context = LoginActivity.this;
        shared = context.getSharedPreferences("userInfo", 0);
        editor = shared.edit();//获取编辑器

        initView();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String pay_result = shared.getString("pay_result", "");
        if ("success".equals(pay_result)){
            Intent intent = new Intent();
            intent.putExtra("login", true);
            setResult(Activity.RESULT_OK, intent);
            editor.putString("pay_result", "");
            editor.commit();//提交修改
            finish();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        ToastView toast;
        switch (view.getId()){
            case R.id.tv_to_weixin:
                // 通过WXAPIFactory工厂，获取IWXAPI的实例
                api = WXAPIFactory.createWXAPI(this, ApiInterface.APP_ID, false);
                // 将该app注册到微信
                api.registerApp(ApiInterface.APP_ID);

                if(!api.isWXAppInstalled()){
                    toast = new ToastView(context, "没有安装微信");
//                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    return;
                }
//                if( !api.isWXAppSupportAPI() ){
//                    toast = new ToastView(context, "请先更新微信应用");
//                    toast.show();
//                    return;
//                }
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                api.sendReq(req);
                break;
            case R.id.iv_back:
                CloseKeyBoard();
                finish();
                break;
            //忘记密码
            case R.id.tv_login_left:
                Toast.makeText(context,"忘记密码",Toast.LENGTH_SHORT).show();
                break;
            //注册
            case R.id.tv_login_right:
                intent = new Intent(context,RegisterActivity.class);
                startActivityForResult(intent, 0);
                break;
            //登录
            case R.id.tv_login:
                phone = et_login_phone.getText().toString().trim();
                pass = et_login_pass.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    toast = new ToastView(context, "请输入手机号");
                    toast.show();
                    return;
                }
                if (TextUtils.isEmpty(pass)){
                    toast = new ToastView(context, "请输入密码");
                    toast.show();
                    return;
                }
                if (!ReflectionUtils.isPassword(pass)) {
                    toast = new ToastView(context, "密码格式错误，请输入长度8-16位数字和字母组合");
                    toast.show();
                    return;
                }
                try {
                    send = new SendRequest();
                    send.phone = phone;
                    send.password = pass;
                    //注册
                    nHttpClient.getAll(ApiInterface.LOGIN_IN, send.toSigninJson().toString(), signinHandler);
                }catch (Exception e){
                    toast = new ToastView(context, "参数错误");
                    toast.show();
                    return;
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (data != null){
                CloseKeyBoard();
                Intent intent = new Intent();
                intent.putExtra("login", true);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        }
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.tv_login_left).setOnClickListener(this);
        findViewById(R.id.tv_login_right).setOnClickListener(this);
        findViewById(R.id.tv_login).setOnClickListener(this);
        findViewById(R.id.tv_to_weixin).setOnClickListener(this);

        et_login_phone = (EditText) findViewById(R.id.et_login_phone);
        et_login_pass = (EditText) findViewById(R.id.et_login_pass);
    }

    private MyHttpClientRespenseHandler signinHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                try {
                    JSONObject jsonObject = json.getJSONObject("data").getJSONObject("user");
                    editor.putString("user_phone", jsonObject.getString("user_phone"));
                    editor.putString("user_id", jsonObject.getString("user_id"));
//                    editor.putString("user_id","14");
                    String user_photo = jsonObject.getString("user_photo");
                    if (user_photo.equals("null")) {
                        user_photo = "";
                    }
                    String user_name = jsonObject.getString("user_name");
                    if (user_name.equals("null")) {
                        user_name = "";
                    }
                    editor.putString("user_photo",user_photo);
                    editor.putString("user_name", user_name);
                    editor.putString("password", jsonObject.getString("user_password"));
                    editor.commit();//提交修改
                    CloseKeyBoard();
                    Intent intent = new Intent();
                    intent.putExtra("login", true);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    // 关闭键盘
    public void CloseKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_login_phone.getWindowToken(), 0);
    }

}
